package org.makcro.sms.services.chat.base.dao;

import java.util.Date;

import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.persistence.TemporalType;

import org.makcro.sms.services.chat.model.Subscriber;

public class SubscriberDAO extends AbstractDAO<Subscriber> implements SubscriberDao {

	public SubscriberDAO() {
		super(Subscriber.class);

	}

	/* (non-Javadoc)
	 * @see org.makcro.sms.services.chat.base.dao.SubscriberDao#checkIfHasActiveSessionAndUpdate(java.lang.String)
	 */
	@Override
	public boolean checkIfHasActiveSessionAndUpdate(String phonenumber) {
		try {
			// find by phonenumber and active state
			Subscriber result = (Subscriber) entityManager.createNamedQuery("Subscriber.findByPhonenumberAndState").setParameter("phonenumber", phonenumber).setParameter("unsubscribed", false)
					.getSingleResult();

			if (result != null) {
				result.setSubscriptionDate(new Date());
				edit(result);
				return true;
			}
		} catch (NoResultException e) {

		}
		return false;
	}

	/* (non-Javadoc)
	 * @see org.makcro.sms.services.chat.base.dao.SubscriberDao#disableExpiredSubscriptions(java.util.Date)
	 */
	@Override
	public int disableExpiredSubscriptions(Date lastMonth) {
		Query query = entityManager.createNamedQuery("Subscriber.updateExpired");
		query.setParameter("lastMonth", lastMonth, TemporalType.TIMESTAMP);
		int updatedRows = query.executeUpdate();

		return updatedRows;
	}

	/* (non-Javadoc)
	 * @see org.makcro.sms.services.chat.base.dao.SubscriberDao#disableSubscription(java.lang.String)
	 */
	@Override
	public int disableSubscription(String phonenumber){
		return entityManager.createNamedQuery("Subscriber.unsubscribeByPhonenumber").setParameter("phonenumber", phonenumber).executeUpdate();
	}
	
	/* (non-Javadoc)
	 * @see org.makcro.sms.services.chat.base.dao.SubscriberDao#findByPhonenumber(java.lang.String)
	 */
	@Override
	public Subscriber findByPhonenumber(String phonenumber) {

		try {
			Subscriber subsciber = (Subscriber) entityManager.createNamedQuery("Subscriber.findByPhonenumber").setParameter("phonenumber", phonenumber).getSingleResult();
			return subsciber;
		} catch (NoResultException e) {
			return null;
		}
	}
}
